package com.zzyl.framework.interceptor;

import com.zzyl.common.utils.MemberThreadLocal;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author:zhq
 * @Date: 2025/08/20 15:49
 * @Description:
 */
@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //获取token
        String token = request.getHeader("authorization");
        if(StringUtils.isBlank(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        try {
            Claims claims = tokenService.parseToken(token);
            if(Objects.isNull(claims)){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            Object memberId = claims.get("userid");
            if(Objects.isNull(memberId)){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            MemberThreadLocal.setMemberId(Long.valueOf(memberId.toString()));
            log.info("小程序端登录的老人家属id:{}", memberId);
        } catch (Exception e) {
            log.error("token解析异常:{}",e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MemberThreadLocal.remove();
    }
}
